package com.cn.ant.modules.wechat.web;

import com.cn.ant.modules.wechat.entity.WeixinAccount;
import com.cn.ant.modules.wechat.service.WechatService;
import com.cn.ant.modules.wechat.service.WeixinAccountServiceImpl;
import com.cn.ant.modules.wechat.utils.SignUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 微信公众号对接接口
 */
@Controller
@RequestMapping("${wechat}/wechatController")
public class WechatController {

    @Autowired
    private WeixinAccountServiceImpl accountService;
    @Autowired
    private WechatService wechatService;

    /**
     * 接入微信公众号
     * @param request
     * @param response
     * @param signature 微信加密签名
     * @param timestamp 时间戳
     * @param nonce 随机数
     * @param echostr 随机字符串
     */
    @RequestMapping(value="wechat", method = RequestMethod.GET)
    public void wechatGet(HttpServletRequest request,HttpServletResponse response, @RequestParam(value = "signature") String signature,
                          @RequestParam(value = "timestamp") String timestamp, @RequestParam(value = "nonce") String nonce,
                          @RequestParam(value = "echostr") String echostr) {
        List<WeixinAccount> weixinAccountList = accountService.queryForList(null);
        for (WeixinAccount weixinAccount : weixinAccountList) {
            if (SignUtil.checkSignature(weixinAccount.getAccountToken(), signature,
                    timestamp, nonce)) {
                try {
                    response.getWriter().print(echostr);
                    break;
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    @RequestMapping(value = "wechat", method = RequestMethod.POST)
    public void wechatPost(HttpServletResponse response,HttpServletRequest request) throws IOException {
        String respMessage = wechatService.coreService(request);
        PrintWriter out = response.getWriter();
        out.print(respMessage);
        out.close();
    }
}